const { Controller } = require('egg');

class TopicsController extends Controller {

  async index() {

    const { ctx } = this;

    const validateRule = {
      page: 'number',
      pageSize: 'number',
      title: 'string?',
    };
    ctx.validate(validateRule, ctx.request.body);

    const { rows, count, page, pageSize } = await ctx.service.topics.index(ctx.request.body);

    ctx.status = 200;
    ctx.body = {
      rows,
      page,
      pageSize,
      total: count,
    };

  }

  async create() {
    const { ctx } = this;

    const validateRule = {
      title: 'string',
      tab: { type: 'enum', values: [ 'ask', 'share', 'job' ], required: false },
      content: 'string',
    };

    ctx.validate(validateRule, ctx.request.body);

    const topic_id = await ctx.service.topics.create(ctx.request.body);

    ctx.body = {
      topic_id,
    };
    ctx.status = 200;

  }

  async update() {
    const { ctx } = this;

    const validateRule = {
      id: 'string?',
      tab: 'enum?',
      content: 'string?',
    };

    ctx.validate(validateRule, ctx.request.body);

    const id = ctx.params.id || 0;

    const obj = await ctx.service.topics.update(id, ctx.request.body);

    if (obj) {
      ctx.body = obj;
    } else {
      ctx.body = {
        msg: '未找到该数据',
      };
    }
    ctx.status = 200;

  }


  async destroy() {
    const { ctx } = this;
    const id = ctx.params.id || 0;

    const delId = await ctx.service.topics.destroy(id);

    ctx.status = 200;
    ctx.body = { delId };
  }

  async show() {
    const { ctx } = this;
    const id = ctx.params.id || 0;
    const data = await ctx.service.topics.show(id);
    ctx.body = data;
  }

  // 还有 new edit 方法， 如果业务需要可以添加

}

module.exports = TopicsController;
